﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;

namespace TestCrawler.Parser
{
    public class UrlParser : IParser
    {
        private string _serverUrl;
        private string _pathUrl;
        private string _content;

        public UrlParser(string serverUrl, string pathUrl, string content)
        {
            _serverUrl = serverUrl;
            _pathUrl = pathUrl;
            _content = content;
        }

        public IList<string> GetHrefs()
        {
            Regex r = new Regex("href.*?\"(?<href>.*?)\"",
                RegexOptions.IgnoreCase | RegexOptions.Singleline);

            MatchCollection mc = r.Matches(_content);

            List<string> hrefs = new List<string>();

            foreach (Match m in mc)
            {
                string href = m.Groups["href"].Value;
                href.Trim();

                if (href != "")
                {
                    // if url doesn't start with ... 
                    if (FromLeft(href, 1) != "#")
                    {
                        // ... but with.
                        if (FromLeft(href, 1) == "/")
                        {
                            href = _serverUrl + href;
                        }
                        else
                        {
                            // else if no http beginning...
                            if (String.Compare(FromLeft(href, 7), "http://", true) != 0)
                            {
                                // ... but begin with www.
                                if (String.Compare(FromLeft(href, 3), "www", true) == 0)
                                { 
                                    href = "http://" + href;
                                }
                                else
                                {
                                    href = _pathUrl + href;
                                } // end else
                            } // end if 
                        } // end else
                    } // end if

                    hrefs.Add(href);

                } // end if
            } // end foreach

            return hrefs;
        }

        /// <summary>
        /// Check if href is longer than string to compare.
        /// If true, return string of same size as comparing string.
        /// </summary>
        private string FromLeft(string href, int comparingLength)
        {
            if (href.Length > comparingLength)
            {
                href = href.Substring(0, comparingLength);
            } // end if

            return href;
        }
    }
}
